import * as api from '@/services/checkTask';
import * as apiCheckServer from '@/services/checkServer';
import * as apiTemplate from '@/services/nodeTemplate';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable, { EditableProTable } from '@ant-design/pro-table';
import { Badge, Button, Card, Checkbox, Col, Divider, Popconfirm, Radio, Row, Tabs, Tag, message } from 'antd';
import TabPane from 'antd/lib/tabs/TabPane';
import React, { useEffect, useRef, useState } from 'react';
import dayjs from 'dayjs';
import * as utils from '@/utils/utils';
import * as c from '@/services/consts';
import { ProFormDependency, ProFormSelect } from '@ant-design/pro-components';
import { Space } from 'antd/lib';
import { CheckboxChangeEvent } from 'antd/es/checkbox';

type VpnServerFormProps = {
  visible: boolean;
  groupIds: string[];
  instIds: number[];
  groups: API.VpnGroupMonitorModel[] | API.NodeGroupMonitorModel[];
  servers: API.VpnServerMonitorModel[] | API.NodeMonitorModel[];
  onCancel: () => void;
  onSubmit: () => Promise<void>;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, groupIds, instIds, groups, servers, onCancel, onSubmit } =
    props;

  if (!visible) {
    return null;
  }

  // console.log(groupIds, groups, instIds, servers);

  const [myloading, setMyloading] = useState<boolean>(true);
  // const [dataSource, setDataSource] = useState<API.CheckTask | undefined>(undefined,);
  const [dataCheckers, setDataCheckers] = useState<API.CheckServer[] | undefined>(undefined);
  const [dataTemplets, setDataTemplets] = useState<API.NodeTemplate[] | undefined>(undefined);
  const [checkedList, setCheckedList] = useState<any[]>([]);
  const [checkeBlock, setCheckeBlock] = useState<boolean>(false);
  // const [checkJob, setCheckJob] = useState<string|undefined>('checknode');
  const [groupEditableKeys, setGroupEditableKeys] = useState<React.Key[]>(() =>groupIds.map((item) => item),);
  const [serverEditableKeys, setServerEditableKeys] = useState<React.Key[]>(() => instIds.map((item) => item),);
  // const [changeCheckedList, setChangeCheckedList] = useState<any[]>([]);
  const [checkedTempletList, setCheckedTempletList] = useState<any[]>([]);

  const formRef = useRef<ProFormInstance>();
  // const editorFormRef = useRef<EditableFormInstance<API.VpnServerNet>>();

  const loadData = async () => {
    // const result = await api.get();
    // if (result && result.success) {
    //   // console.log(result);
    //   setDataSource(result.data);
    //   // setChangeCheckedList(() => result.data.s?.map((item) => item.id));
    // }

    const resultChecker = await apiCheckServer.list();
    if (resultChecker && resultChecker.data) {
      let checkerIds = [];
      for(let d of resultChecker.data){
        if(d.isDefault == true){
          checkerIds.push(d.id);
        }
      }
      setCheckedList(checkerIds);
      setDataCheckers(resultChecker.data);
    } else {
      setDataCheckers([]);
    }


    let resultTemplet = await apiTemplate.all(undefined, undefined, undefined);
    if(resultTemplet && resultTemplet.success){
      setDataTemplets(resultTemplet.data);
    }

    setMyloading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleFormSubmit = async () => {
    
    var job = formRef?.current?.getFieldValue('job');
    var mode = formRef?.current?.getFieldValue('mode');
    var level = formRef?.current?.getFieldValue('level');
    // console.log(job,mode, level);
    
    if(!checkedList || checkedList.length == 0){
      message.error("请选择用于检测的服务器");
      return;
    }
    if(!job){
      message.error("请选择检测类型");
      return;
    }
    if(!level){
      message.error("请选择检测级别");
      return;
    }

    // console.log(groupEditableKeys, serverEditableKeys);
    let data = {
      groupIds: groupEditableKeys.map((val) => val.toString()),
      instIds: serverEditableKeys.map((val) => val as number),
      templetIds: checkedTempletList,
      serverIds: checkedList,
      checkBlock: checkeBlock,
      job: job,
      mode: mode,
      level: level,
    };
    // console.log(data);
    // return;
    const result = await api.create(data);
    if (result && result.success) {
      onSubmit();
    }
  };
  
  // const handleChangeCheckerSubmit = async () => {
  //   if(!changeCheckedList || changeCheckedList.length == 0){
  //     message.error("请选择用于检测的服务器");
  //     return;
  //   }
  //   let data = {
  //     checkers: changeCheckedList,
  //   };
  //   const result = await api.updateServer(data);
  //   if (result && result.success) {
  //     onSubmit();
  //   }
  // };

  const newGroupColumns: ProColumns<API.VpnGroupMonitorModel | API.NodeGroupMonitorModel>[] = [
    // {
    //   title: 'ID',
    //   dataIndex: 'id',
    //   width:100,
    // },
    {
      title: '名称',
      dataIndex: 'name',
      readonly: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
    },
  ];
  
  const checkAll = dataCheckers?.length === checkedList?.length;
  const indeterminate = checkedList?.length > 0 && checkedList?.length < dataCheckers?.length;
  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    setCheckedList(e.target.checked ? dataCheckers?.map((val)=>val.id) : []);
  };

  const newServerColumns: ProColumns<API.VpnServerMonitorModel | API.NodeMonitorModel>[] = [
    {
      title: '实例ID',
      dataIndex: 'instanceId',
      readonly: true,
      width: 200,
    },
    {
      title: '名称',
      dataIndex: 'name',
      readonly: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
    },
  ];


  return (
    <DrawerForm<API.CheckTask>
      open={visible}
      title='下发检测'
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      // submitter={{
      //   render: (props, defaultDoms) => {
      //     return [defaultDoms[0]];
      //   },
      // }}
      loading={myloading}
    >
            <Row gutter={24} style={{marginTop:10}}>
              <Col span={4}>
                <ProFormSelect
                  name='level'
                  label="任务等级"
                  allowClear={false}
                  options={c.CheckLevelOptions}
                  mode='single'
                  initialValue={c.CheckLevel.Normal.value}
                />
              </Col>
              <Col span={4}>
                <ProFormSelect
                  name='job'
                  label="检测类型"
                  allowClear={false}
                  options={c.CheckJobOptions}
                  mode='single'
                  initialValue={c.CheckJob.CheckNode.value}
                  fieldProps={{
                    listHeight:600
                  }}
                />
              </Col>
              <ProFormDependency name={['job']}>
                {({ job }) => {
                  if (job == c.CheckJob.CheckNode.value) {
                    return (
                    <Col span={4}>
                      <ProFormSelect
                        name='mode'
                        label="检测模式"
                        allowClear={false}
                        options={c.CheckModeOptions}
                        mode='single'
                        initialValue={c.CheckMode.Simple.value}
                        fieldProps={{
                          listHeight:600
                        }}
                      />
                    </Col>
                    );
                  }
                  return null;
                }}
              </ProFormDependency>
              <Col span={3} style={{paddingTop:35}}>
                <Checkbox
                  checked={checkeBlock}
                  onChange={(e) => {
                    setCheckeBlock(e.target.checked);
                  }}
                >
                  检测被墙
                </Checkbox>
              </Col>
              <Col span={3} style={{paddingTop:30}}>
              </Col>
            </Row>

            <Divider orientation="left" orientationMargin={0}>检测服务器</Divider>
            <Row gutter={24}>
              <Col span={24}>
                <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>全选</Checkbox>
              </Col>
            </Row>
            <Checkbox.Group key="ckgPlat" onChange={setCheckedList} value={checkedList}>
              <Row gutter={24}>
              {dataCheckers?.map((gc) => {
                let text = <Tag color={gc.online == true ? 'green' : 'error'}>{gc.name} [{gc.id}]</Tag>;
                return (
                  <Col span={6}><Checkbox value={gc.id} style={{ verticalAlign: 'middle' }}>
                    {gc.status ? (
                      <Badge color="#52c41a" text={text} />
                    ) : (
                      <Badge color="#f50" text={text} />
                    )}
                  </Checkbox></Col>
                );
              })}</Row>
            </Checkbox.Group>

            
            <Divider orientation="left" orientationMargin={0} style={{marginTop:40}}>节点模板</Divider>
            <Checkbox.Group key="ckgTemplet" onChange={setCheckedTempletList} value={checkedTempletList}>
              {dataTemplets?.map((gc) => {
                return (
                  <Checkbox value={gc.id} style={{ verticalAlign: 'middle' }}>
                    <Tag color='blue'>{gc.name}</Tag>
                  </Checkbox>
                );
              })}
            </Checkbox.Group>
            
            <Divider orientation="left" orientationMargin={0} style={{marginTop:40}}>检测分组</Divider>
            <EditableProTable<API.VpnGroupMonitorModel | API.NodeGroupMonitorModel>
              rowKey="id"
              // editableFormRef={editorFormRef}
              // headerTitle="分组"
              locale={{ emptyText: '暂无数据' }}
              // toolBarRender={false}
              columns={newGroupColumns}
              defaultValue={groups}
              // onChange={setDataSource}
              recordCreatorProps={false}
              editable={{
                type: 'multiple',
                editableKeys: groupEditableKeys,
                actionRender: (row, config, defaultDom) => [
                  defaultDom.delete,
                ],
                // onValuesChange: (record, recordList) => {
                //   //setDataSource(recordList);
                // },
                onChange: setGroupEditableKeys,
              }}
            />
            
            <Divider orientation="left" orientationMargin={0}>检测服务器</Divider>

              <EditableProTable<API.VpnServerMonitorModel | API.NodeMonitorModel>
                rowKey="instanceId"
                // headerTitle="服务器"
                locale={{ emptyText: '暂无数据' }}
                columns={newServerColumns}
                defaultValue={servers}
                recordCreatorProps={false}
                editable={{
                  type: 'multiple',
                  editableKeys: serverEditableKeys,
                  actionRender: (row, config, defaultDom) => [
                    defaultDom.delete,
                  ],
                  onChange: setServerEditableKeys,
                }}
              />         




    </DrawerForm>
  );
};

export default VpnServerForm;
